package com.cloud.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;

import java.lang.reflect.Field;

/**
 * 反射工具
 *
 * @author fengwenjin
 */
@Slf4j
public class ReflectUtils {

    /**
     * 动态设置对象私有属性值
     *
     * @param instance
     * @param name
     * @param value
     */
    public static void setField(Object instance, String name, Object value) {
        try {
            if (AopUtils.isAopProxy(instance)) {
                TargetSource targetSource = ((Advised) instance).getTargetSource();
                instance = targetSource.getTarget();
            }
            Field field = instance.getClass().getDeclaredField(name);
            if (field != null) {
                field.setAccessible(true);
                field.set(instance, value);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
